package com.g8.pethospitallearnbackend.service.impls;

import com.g8.pethospitallearnbackend.entity.*;
import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.mapper.*;
import com.g8.pethospitallearnbackend.service.PaperService;
import com.g8.pethospitallearnbackend.utils.NewIdGenerateUtil;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class PaperServiceImpl implements PaperService {
    @Autowired
    PaperMapper paperMapper;
    @Autowired
    PaperQuestionMapper paperQuestionMapper = null;
    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    ExamMapper examMapper;

    @Autowired
    ExamInternMapper examInternMapper;

    @Override
    public List<Paper> getAllPaper() {
        PaperExample paperExample = new PaperExample();
        List<Paper> list = paperMapper.selectByExample(paperExample);
        for(int i=0;i<list.size();i++){
            Paper paper = list.get(i);
            String paperId = paper.getPaperId();
            paper = getPaperById(paperId);
            list.get(i).setPaperQuesList(paper.getPaperQuesList());
        }
        return list;
    }

    @Override
    public Paper getPaperById(String paperId) {
        if (paperId == null || paperId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "请求ID为空，请补充完整！");
        }

        Paper paper = paperMapper.selectByPrimaryKey(paperId);
        if (paper == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "该试卷不存在！");
        }

        //根据paperId在paperQuestion表中搜索和试卷有关的题目，返回一个List的PaperQuestion
        PaperQuestionExample paperQuestionExample = new PaperQuestionExample();
        paperQuestionExample.setOrderByClause("ques_id");
        paperQuestionExample.createCriteria().andPaperIdEqualTo(paperId);
        List<PaperQuestion> list1 = paperQuestionMapper.selectByExample(paperQuestionExample);
        //HashMap<Question,Integer> hashMap = new HashMap<>();
        /*对上面返回的PaperQuestion的List进行处理，把题目的id（需要进行一步搜索）、题目的具体信息、题目的分值拿出来
        放在新增类PaperQues的List里，方便返回前端所需要的信息*/
        List<Paper.PaperQues> paperQuesList = new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            String qpk = list1.get(i).getQuesId();
            Question question = questionMapper.selectByPrimaryKey(qpk);
            int sc = list1.get(i).getScore();
            Paper.PaperQues paperQues = new Paper.PaperQues(question, sc);
            paperQuesList.add(paperQues);
        }
        if (paper != null)
            paper.setPaperQuesList(paperQuesList);
        return paper;
    }

    @Override
    public List<Paper> searchPaper(String searchPaper) {
        searchPaper = "%" + searchPaper + "%";
        PaperExample paperExample = new PaperExample();
        paperExample.createCriteria().andPaperNameLike(searchPaper);
        List<Paper> papers = paperMapper.selectByExample(paperExample);
        if (papers.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "你搜索的试卷不存在，换个关键词试试吧!");
        }
        return papers;
    }

    @Override
    public Paper addPaper(Paper paper) {
        //判断所填信息是否完整
        if (paper.getPaperName() == null || paper.getPaperName().isEmpty()
                || paper.getPaperScore() == null || paper.getPaperScore().toString().isEmpty()
                || paper.getPaperQuesList() == null || paper.getPaperQuesList().isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增试卷信息不完整，请补充完整后添加");
        }

        //试卷名称不允许重复
        PaperExample paperExample11 = new PaperExample();
        paperExample11.createCriteria().andPaperNameEqualTo(paper.getPaperName());
        List<Paper> paperList11 = paperMapper.selectByExample(paperExample11);
        if(!paperList11.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增试卷名字重复，请重新取名");
        }

        if (paper.getPaperName().toString().length() >= 30) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "试卷名过长，请修改！");
        }
        //判断添加的所有题目的总分加起来与试卷分数是否一致
        List<Paper.PaperQues> paperQuesList = paper.getPaperQuesList();
        int total = 0;
        for (int i = 0; i < paperQuesList.size(); i++) {
            if (paperQuesList.get(i).getScore() == null || paperQuesList.get(i).getScore().toString().isEmpty()
                    || paperQuesList.get(i).getQuestion() == null || paperQuesList.get(i).getQuestion().toString().isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增试卷题目或分值不完整，请补充完整后添加");
            }
            total += paperQuesList.get(i).getScore();
        }
        if (total != paper.getPaperScore()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "试卷总分与题目的所有分值不相等，请调整后添加");
        }
        //随机生成paperId
        String id = NewIdGenerateUtil.getNumber(3);
        Paper repeat = paperMapper.selectByPrimaryKey(id);
        while (repeat != null) {
            id = NewIdGenerateUtil.getNumber(3);
            repeat = paperMapper.selectByPrimaryKey(id);
        }
        paper.setPaperId(id);
        //处理试卷中的题目列表
        for (int i = 0; i < paperQuesList.size(); i++) {
            //遍历
            Paper.PaperQues paperQues = paperQuesList.get(i);
            //对于每一个PaperQues，将其question补充完整
            String quesId = paperQues.getQuestion().getQuesId();
            Question question = questionMapper.selectByPrimaryKey(quesId);
            if (question == null) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您选择的题目不存在，请重新选择");
            }
            paperQues.setQuestion(question);
//            //将添加的试卷与题目信息存储到paper_question表中
//            PaperQuestion paperQuestion = new PaperQuestion();
//            paperQuestion.setPaperId(paper.getPaperId());
//            paperQuestion.setQuesId(quesId);
//            paperQuestion.setScore(paperQues.getScore());
//            paperQuestionMapper.insert(paperQuestion);
            //这里原来出错喽，因为paper_question中有外键约束，所以要先把paper插入再进行以上步骤
        }
        paperMapper.insert(paper);
        for (int i = 0; i < paperQuesList.size(); i++) {
            //遍历
            Paper.PaperQues paperQues = paperQuesList.get(i);
            String quesId = paperQues.getQuestion().getQuesId();
            //将添加的试卷与题目信息存储到paper_question表中
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paper.getPaperId());
            paperQuestion.setQuesId(quesId);
            paperQuestion.setScore(paperQues.getScore());
            paperQuestionMapper.insert(paperQuestion);
        }
        return paper;
    }

    @Override
    public Paper changePaper(Paper paper) {
        //判断所填信息是否完整
        if (paper.getPaperName() == null || paper.getPaperName().isEmpty()
                || paper.getPaperScore() == null || paper.getPaperScore().toString().isEmpty()
                || paper.getPaperQuesList() == null || paper.getPaperQuesList().isEmpty()
                || paper.getPaperId() == null || paper.getPaperId().isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增试卷信息不完整，请补充完整后添加");
        }

        //试卷名称不允许重复
        PaperExample paperExample11 = new PaperExample();
        paperExample11.createCriteria().andPaperNameEqualTo(paper.getPaperName()).andPaperIdNotEqualTo(paper.getPaperId());
        List<Paper> paperList11 = paperMapper.selectByExample(paperExample11);
        if(!paperList11.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增试卷名字重复，请重新取名");
        }

        //判断该试卷是否被考试所引用，如果被引用且已经有考生参加则不能修改
        ExamExample examExample = new ExamExample();
        examExample.createCriteria().andPaperIdEqualTo(paper.getPaperId());
        List<Exam> examList = examMapper.selectByExample(examExample);
        for (int i = 0; i < examList.size(); i++) {
            String examId = examList.get(i).getExamId();
            ExamInternExample examInternExample = new ExamInternExample();
            examInternExample.createCriteria().andExamIdEqualTo(examId).andEnterTimeIsNotNull();
            List<ExamIntern> examInterns = examInternMapper.selectByExample(examInternExample);
            if (!examInterns.isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST,
                        "你所要修改的试卷已经被考试引用，并且已有考生参加，不能修改了呦~");
            }
        }


        //查找数据库中是否有该试卷
        String paperId = paper.getPaperId();
        Paper paper1 = paperMapper.selectByPrimaryKey(paperId);
        if (paper1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "你所要修改的试卷不存在，请重新选择");
        }

        //判断添加的所有题目的总分加起来与试卷分数是否一致
        List<Paper.PaperQues> paperQuesList = paper.getPaperQuesList();
        int total = 0;
        for (int i = 0; i < paperQuesList.size(); i++) {
            if (paperQuesList.get(i).getScore() == null || paperQuesList.get(i).getScore().toString().isEmpty()
                    || paperQuesList.get(i).getQuestion() == null || paperQuesList.get(i).getQuestion().toString().isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增试卷题目或分值不完整，请补充完整后添加");
            }
            total += paperQuesList.get(i).getScore();
        }
        if (total != paper.getPaperScore()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "试卷总分与题目的所有分值不相等，请调整后添加");
        }

        //处理试卷中的题目列表
        for (int i = 0; i < paperQuesList.size(); i++) {
            //遍历
            Paper.PaperQues paperQues = paperQuesList.get(i);
            //对于每一个PaperQues，将其question补充完整
            String quesId = paperQues.getQuestion().getQuesId();
            Question question = questionMapper.selectByPrimaryKey(quesId);
            if (question == null) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您选择的题目不存在，请重新选择");
            }
            paperQues.setQuestion(question);
        }

        //修改数据库中的paper
        paperMapper.updateByPrimaryKey(paper);


        //更新paper_question表
        //先把paperId的全都删除，然后重新添加
        PaperQuestionExample paperQuestionExample = new PaperQuestionExample();
        paperQuestionExample.createCriteria().andPaperIdEqualTo(paperId);
        paperQuestionMapper.deleteByExample(paperQuestionExample);
        for (int i = 0; i < paperQuesList.size(); i++) {
            //遍历
            Paper.PaperQues paperQues = paperQuesList.get(i);
            String quesId = paperQues.getQuestion().getQuesId();
            //将添加的试卷与题目信息修改到paper_question表中
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paper.getPaperId());
            paperQuestion.setQuesId(quesId);
            paperQuestion.setScore(paperQues.getScore());

            //重新添加
            paperQuestionMapper.insert(paperQuestion);
        }

        return paper;
    }

    @Override
    public String deletePaper(String paperId) {
        //检查要删除的试卷是否在数据库中
        Paper paper = paperMapper.selectByPrimaryKey(paperId);
        if (paper == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要删除的试卷不存在，请重新选择");
        }

        //判断该试卷是否被考试所引用，如果被引用且已经有考生参加则不能修改
        ExamExample examExample = new ExamExample();
        examExample.createCriteria().andPaperIdEqualTo(paper.getPaperId());
        List<Exam> examList = examMapper.selectByExample(examExample);
        for (int i = 0; i < examList.size(); i++) {
            String examId = examList.get(i).getExamId();
            ExamInternExample examInternExample = new ExamInternExample();
            examInternExample.createCriteria().andExamIdEqualTo(examId).andEnterTimeIsNotNull();
            List<ExamIntern> examInterns = examInternMapper.selectByExample(examInternExample);
            if (!examInterns.isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST,
                        "你所要修改的试卷已经被考试引用，并且已有考生参加，不能修改了呦~");
            }
        }

        //检查输入的paperId是否为空
        if (paperId == null || paperId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您输入的paperId为空，请重新选择");
        }
        paperMapper.deleteByPrimaryKey(paperId);
        return "删除成功";
    }
}
